import React, { useState, useCallback, useEffect } from 'react';
import { View, Text } from '@ray-js/ray';
import { NavBar } from '@ray-js/smart-ui';
import styles from './index.module.less';
import { Cell, CellGroup } from '@ray-js/smart-ui';
import { Icon } from '@ray-js/smart-ui';
import Mic from '@tuya-miniapp/icons/dist/svg/Mic';

import { putDpData } from '@/utils/sendDp';
import { connectBLEDevice } from '@/utils/ble';
import { dpCodes, globalConfig } from '@/config';

import { getLaunchOptionsSync } from '@ray-js/ray';
import { getDpsInfos, getLaunchOptionsSync } from '@ray-js/ray';

import {
  showToast,
  onDpDataChange,
  offDpDataChange,
  deleteTemporaryPassword,
  createTemporaryPassword,
  updateTempPassword,
} from '@ray-js/ray';

// 假设 dpCodes 里有 vibration_wakeup 这个 DP 点
const { voice_switch, vibration_switch, vibration_wakeup } = dpCodes;

export function SettingPage() {
  const [isSwitchOn, setIsSwitchOn] = useState(false);
  const [isVibrateSwitchOn, setIsVibrateSwitchOn] = useState(false);
  // 新增震动唤醒开关状态
  const [isVibrationWakeupOn, setIsVibrationWakeupOn] = useState(false);

  const handleSwitchToggle = () => {
    setIsSwitchOn(!isSwitchOn);
    console.log(`Switch is now ${isSwitchOn ? 'off' : 'on'}`);
    putDpData(voice_switch, !isSwitchOn);
  };

  const handleVibrateSwitchToggle = () => {
    setIsVibrateSwitchOn(!isVibrateSwitchOn);
    console.log(`Vibrate Switch is now ${isVibrateSwitchOn ? 'off' : 'on'}`);
    putDpData(vibration_switch, !isVibrateSwitchOn);
  };

  // 新增震动唤醒开关切换函数
  const handleVibrationWakeupToggle = () => {
    setIsVibrationWakeupOn(!isVibrationWakeupOn);
    console.log(`Vibration Wakeup Switch is now ${isVibrationWakeupOn ? 'off' : 'on'}`);
    putDpData(vibration_wakeup, !isVibrationWakeupOn);
  };

  // 定义 DP 数据变化处理函数
  const handleDpDataChange = ({ dpCode, dpValue }) => {
    // 根据变化的 DP 点进行不同的处理
    // console.log(`DP Code: ${dpCode}, DP Value: ${dpValue}`);
    // console.log(`DP Code: ${dpCode}, DP Value: ${dpValue}`);
    console.log(typeof(dpCode));

    if (dpCode === '101') {       // 声音开关
      console.log(`bjhDP Code: ${dpCode}, DP Value: ${dpValue}`);
      setIsSwitchOn(dpValue);
    } 

    if (dpCode === '102') {       // 震动开关
      console.log(`bjhDP Code: ${dpCode}, DP Value: ${dpValue}`);
      setIsVibrateSwitchOn(dpValue);
    }

    // 新增震动唤醒 DP 点处理
    if (dpCode === '108') {       // 假设震动唤醒 DP 点为 103，按需修改
      console.log(`bjhDP Code: ${dpCode}, DP Value: ${dpValue}`);
      setIsVibrationWakeupOn(dpValue);
    }
  };

  // 注册监听器
  useEffect(() => {
    const dpDataChangeHandler = ({ dps }) => {
      // 遍历每个变化的 DP 点
      Object.entries(dps).forEach(([dpCode, dpValue]) => {
        handleDpDataChange({ dpCode, dpValue });
      });
    };

    onDpDataChange(dpDataChangeHandler);

    const { deviceId } = getLaunchOptionsSync().query || {};
    if (deviceId) {
      // 获取设备所有 DP 信息
      getDpsInfos({
        devId: deviceId,
        gwId: deviceId
      })
      .then((res) => {
        console.log('获取到的所有 DP 信息:', res);
        res.forEach((item) => {
          const { dpId, value } = item;
          // 处理布尔类型的字符串值，转换为布尔值
          let processedValue = value;
          if (typeof value === 'string' && (value === 'true' || value === 'false')) {
            processedValue = value === 'true';
          }
          // 将 dpId 转换为字符串
          const dpCodeStr = String(dpId);
          // console.log(`DP Code: ${code}, DP Value: ${processedValue}`);
          handleDpDataChange({ dpCode: dpCodeStr, dpValue: processedValue });
        });
      })
      .catch((error) => {
        console.error('获取 DP 信息失败:', error);
      });
    } else {
      console.error('无法获取设备 ID');
    }

    // 清理函数，组件卸载时执行
    return () => {
      offDpDataChange(dpDataChangeHandler);
    };
  }, []);

  return (
    <>
      <NavBar
        title="云图香氛机"
        leftArrow
        className={styles.title_css_index}
        border={false}
      />

      <View className={`${styles.container} ${styles.horizontal_layout}`}>
        <View className={styles.setting_background}>
          <View className={styles.sound_info}>
            <Icon name={Mic} size="30px" />
            <Text className={styles.sound_text}>声音</Text>
          </View>
          <View className={styles.switch_wrapper}>
            <View
              className={`${styles.switch} ${isSwitchOn ? styles.switchOn : ''}`}
              onClick={handleSwitchToggle}
            >
              <View className={`${styles.switchLine} ${isSwitchOn ? styles.lineGrow : styles.lineShrink}`} />
              <View className={`${styles.switchSlider} ${isSwitchOn ? styles.sliderOn : ''}`} />
              <View className={`${styles.switchLine} ${isSwitchOn ? styles.lineShrink : styles.lineGrow}`} />
            </View>
          </View>
        </View>

        {/* 新增震动开关容器 */}
        <View className={styles.setting_vibrate}>
          <View className={styles.vibrate_info}>
            {/* 假设存在震动图标，按需替换 */}
            {/* <Icon name="vibrate" size="30px" />  */}
            <Icon name={Mic} size="30px" />
            <Text className={styles.vibrate_text}>触摸震动</Text>
          </View>
          <View className={styles.switch_wrapper}>
            <View
              className={`${styles.switch} ${isVibrateSwitchOn ? styles.switchOn : ''}`}
              onClick={handleVibrateSwitchToggle}
            >
              <View className={`${styles.switchLine} ${isVibrateSwitchOn ? styles.lineGrow : styles.lineShrink}`} />
              <View className={`${styles.switchSlider} ${isVibrateSwitchOn ? styles.sliderOn : ''}`} />
              <View className={`${styles.switchLine} ${isVibrateSwitchOn ? styles.lineShrink : styles.lineGrow}`} />
            </View>
          </View>
        </View>

        {/* 新增震动唤醒开关容器 */}
        <View className={styles.setting_vibration_wakeup}>
          <View className={styles.vibration_wakeup_info}>
            <Icon name={Mic} size="30px" />
            <Text className={styles.vibration_wakeup_text}>震动唤醒</Text>
          </View>
          <View className={styles.switch_wrapper}>
            <View
              className={`${styles.switch} ${isVibrationWakeupOn ? styles.switchOn : ''}`}
              onClick={handleVibrationWakeupToggle}
            >
              <View className={`${styles.switchLine} ${isVibrationWakeupOn ? styles.lineGrow : styles.lineShrink}`} />
              <View className={`${styles.switchSlider} ${isVibrationWakeupOn ? styles.sliderOn : ''}`} />
              <View className={`${styles.switchLine} ${isVibrationWakeupOn ? styles.lineShrink : styles.lineGrow}`} />
            </View>
          </View>
        </View>
        
      </View>
    </>
  );
}